# -*- coding: utf-8 -*-
# @Time   : 2024-05-23 20:04
# @Author : 大龙 🚀
import json

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
from utils.tools import urlencode, replace_str


class GxNnsczjA156Policy(BaseTaxPolicySpider):
    name = 'gx_nnsczj_a156_policy'

    province = "广西壮族自治区"
    city = "南宁市"
    county = ""
    park = ""
    source = "南宁市财政局"

    def start_requests(self):
        page_url = 'https://nncz.nanning.gov.cn/zfxxgkzl/fdzdgknr/zcwj/index1.html?fwjgdz=%E5%8D%97%E8%B4%A2%E8%A7%84'
        url = "https://nncz.nanning.gov.cn/search/search"
        params = {
            "zfwjJsonpCallBack": "zfwjJsonpCallBack",
            "channelid": "212395",
            "siteid": "55",
            "page": "1",
            "fwjgdz": "南财规",
            "": "",
            "_": "1716536865632"
        }
        yield scrapy.Request(url + "?" + urlencode(params), callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        datas = replace_str(response.text, "[;\f\n\r\t\v ​)]", "").replace('zfwjJsonpCallBack(', '').replace('},]',
                                                                                                             '}]')
        for info in json.loads(datas)['page']['content']:
            item = Item()
            item['source_url'] = info['DOCPUBURL']
            item['publish_date'] = info['PUBDATE']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = json.loads(datas)['page']['totalPages']
            for page_num in range(2, int(total_page) + 1):
                url = "https://nncz.nanning.gov.cn/search/search"
                params = {
                    "zfwjJsonpCallBack": "zfwjJsonpCallBack",
                    "channelid": "212395",
                    "siteid": "55",
                    "page": f"{page_num}",
                    "fwjgdz": "南财规",
                    "": "",
                    "_": "1716466161727"
                }
                yield response.follow(url + "?" + urlencode(params), callback=self.parse_list,
                                      meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline
    cmdline.execute("scrapy crawl gx_nnsczj_a156_policy".split())
